<template>
  <div class="container-wrapper">
    <BasicTable
      ref="tableRef"
      :api="getActivityPage"
      :columns="columns"
      :useSearchForm="useSearchForm"
      :actionColumn="actionColumn"
      :pagination="{
        pageString: 'pageNo',
        pageSizeString: 'pageSize'
      }"
    >
      <template #searchFormActions>
        <FormAction :actions="searchFormActions()" />
      </template>
      <template #actions="{ record }">
        <TableAction :actions="tableActions(record.row)" />
      </template>
    </BasicTable>
    <Modal v-model:visible="visible" :title="modalTitle" width="80%" @close="handleModalClose">
      <ModalForm :key="modalKey" ref="modalFormRef" :data="modalData" @success="handleSuccess" />
      <template #footer>
        <el-button type="primary" @click="submitForm">{{
          modalData.modalType === 'detail' ? '关闭' : '保存'
        }}</el-button>
      </template>
    </Modal>
    <Reward :activityId="activityId" v-if="rewardVisabled" @close="rewardVisabled = false" />
  </div>
</template>

<script setup lang="ts">
import { BasicTable, TableAction } from '@/components/BasicTable'
import { FormAction } from '@/components/BasicForm'
import { columns, useSearchForm, actionColumn } from './index.data'
import {
  getActivityPage,
  createActivity,
  updateActivity,
  deleteActivity,
  updateActivityStatus,
  getActivityList
} from '@/api/member/activity'
import { getSpuDetailList } from '@/api/localLife/spu'
import Reward from './Reward.vue'
import Modal from '@/components/Modal/index.vue'
import ModalForm from './ModalForm.vue'
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const visible = ref<boolean>(false)
const modalTitle = ref<string>('新增')
const modalFormRef = ref<InstanceType<typeof ModalForm>>()
const modalData = ref<any>({})
const modalKey = ref<number>(0) // 添加key来强制组件重新渲染
const tableRef = ref<InstanceType<typeof BasicTable>>()
const activityId = ref<number>(0)
const rewardVisabled = ref<boolean>(false)
const tableActions = (row: any) => {
  return [
    {
      label: '详情',
      type: 'text',
      onClick: () => {
        detail(row)
      }
    },
    {
      label: '编辑',
      type: 'text',
      // 编辑按钮是否禁用，如果活动状态处于关闭的情况下，则禁用
      disabled: row.status === 0,
      onClick: () => {
        edit(row)
      }
    },
    {
      label: row.status === 1 ? '关闭' : '开启',
      type: 'text',
      style: row.status === 1 ? 'color: #f00' : '',
      onClick: async () => {
        await updateActivityStatus({
          id: row.id,
          status: row.status === 1 ? 0 : 1
        })
        tableRef.value?.reload()
      }
    },
    {
      label: '删除',
      type: 'text',
      onClick: () => {
        deleteData(row)
      }
    },
    {
      label: '查看记录',
      type: 'text',
      onClick: () => {
        viewRecord(row)
      }
    }
  ]
}

const viewRecord = async (row: any) => {
  activityId.value = row.id
  rewardVisabled.value = true
}
const searchFormActions = () => {
  return [
    {
      label: '新增',
      type: 'primary',
      disabled: isAddDisabled.value,
      onClick: () => add()
    }
  ]
}

const isAddDisabled = computed(() => {
  const tableData = tableRef.value?.dataSource || []
  const currentTime = new Date().getTime()

  return (
    Array.isArray(tableData) &&
    tableData.some(
      (item: any) =>
        item.status === 1 && item.startTime <= currentTime && item.endTime >= currentTime
    )
  )
})

// 公共函数：获取并填充商品详情信息
const fillProductDetails = async (res: any) => {
  const info = res.typeConfigs?.find((item: any) => item.activityType?.type === 4)
  if (!info || !info.rules || !Array.isArray(info.rules)) {
    return
  }

  try {
    // 收集所有需要获取详情的商品ID
    const allProductIds = new Set<number>()

    res.typeConfigs?.forEach((item: any) => {
      if (item.activityType?.type === 4 && Array.isArray(item.rules)) {
        item.rules.forEach((rule: any) => {
          if (rule.productId) {
            allProductIds.add(rule.productId)
          }
        })
      }
    })

    // 如果有商品ID，则获取商品详情
    if (allProductIds.size > 0) {
      const productIds = Array.from(allProductIds)

      const spuList = await getSpuDetailList(productIds)

      // 创建商品信息映射表，提高查找效率
      const spuMap = new Map()
      if (Array.isArray(spuList)) {
        spuList.forEach((spu: any) => {
          if (spu && (spu.productId || spu.id)) {
            const key = spu.productId || spu.id
            spuMap.set(key, {
              picUrl: spu.picUrl || '',
              name: spu.name || '',
              price: spu.price || 0,
              marketPrice: spu.marketPrice || 0
            })
          }
        })
      }

      // 填充商品信息
      res.typeConfigs?.forEach((item: any) => {
        if (item.activityType?.type === 4 && Array.isArray(item.rules)) {
          item.rules.forEach((rule: any) => {
            if (rule.productId) {
              const spuInfo = spuMap.get(rule.productId)
              if (spuInfo) {
                // 只有当字段不存在或为空时才赋值
                if (!rule.picUrl) rule.picUrl = spuInfo.picUrl
                if (!rule.name) rule.name = spuInfo.name
                if (!rule.price && rule.price !== 0) rule.price = spuInfo.price
                if (!rule.marketPrice && rule.marketPrice !== 0)
                  rule.marketPrice = spuInfo.marketPrice
              } else {
                // 设置默认值避免显示异常
                if (!rule.picUrl) rule.picUrl = ''
                if (!rule.name) rule.name = '商品信息缺失'
                if (!rule.price && rule.price !== 0) rule.price = 0
                if (!rule.marketPrice && rule.marketPrice !== 0) rule.marketPrice = 0
              }
            }
          })
        }
      })
    }
  } catch (error) {
    // 发生错误时，确保数据结构完整
    res.typeConfigs?.forEach((item: any) => {
      if (item.activityType?.type === 4 && Array.isArray(item.rules)) {
        item.rules.forEach((rule: any) => {
          if (!rule.picUrl) rule.picUrl = ''
          if (!rule.name) rule.name = '获取失败'
          if (!rule.price && rule.price !== 0) rule.price = 0
          if (!rule.marketPrice && rule.marketPrice !== 0) rule.marketPrice = 0
        })
      }
    })
  }
}

const add = () => {
  modalKey.value = Date.now()
  modalData.value = { modalType: 'add' }
  modalTitle.value = '新增会员活动'
  visible.value = true
}

const edit = async (row: any) => {
  const res = await getActivityList({ id: row.id })

  const editData = JSON.parse(JSON.stringify(res))

  await fillProductDetails(editData)

  // 强制重新渲染组件，确保没有缓存数据
  modalKey.value = Date.now()
  modalData.value = { ...editData, modalType: 'edit' }
  modalTitle.value = '编辑会员活动'
  visible.value = true
}

const detail = async (row: any) => {
  const res = await getActivityList({ id: row.id })

  // 深拷贝数据，避免修改原始数据
  const detailData = JSON.parse(JSON.stringify(res))

  // 填充商品详情信息
  await fillProductDetails(detailData)

  // 强制重新渲染组件，确保没有缓存数据
  modalKey.value = Date.now()
  modalData.value = { ...detailData, modalType: 'detail' }
  modalTitle.value = '会员活动详情'
  visible.value = true
}

const deleteData = (row: any) => {
  ElMessageBox.confirm('确定删除该配置吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteActivity(row.id).then(() => {
        ElMessage({
          message: '删除成功',
          type: 'success'
        })
        tableRef.value?.reload()
      })
    })
    .catch(() => {
      ElMessage({
        message: '取消删除',
        type: 'info'
      })
    })
}

const submitForm = () => {
  modalFormRef.value?.submitForm()
}

// 处理弹窗关闭，清理数据防止缓存
const handleModalClose = () => {
  modalData.value = {}
  modalKey.value = Date.now()
}

const handleSuccess = (data: any) => {
  if (modalData.value.modalType === 'detail') {
    visible.value = false
    return
  }
  data.timeRange = null
  // return
  if (data.id) {
    updateActivity(data).then(() => {
      ElMessage({
        message: '更新成功',
        type: 'success'
      })
      tableRef.value?.reload()
    })
  } else {
    createActivity(data).then(() => {
      ElMessage({
        message: '新增成功',
        type: 'success'
      })
      tableRef.value?.reload()
    })
  }
  visible.value = false
}
</script>

<style scoped lang="scss">
.container-wrapper {
  width: 100%;
  height: 100%;
}
</style>
